package com.tianlh.redis;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

/**
 * @author 黑子
 * @Date 2017/12/30 13:48
 */
@Component
public class RedisClient {
    public final static int DEFAULT_REDIS_DB = 0;
    
    @Autowired
    private JedisPool jedisPool;

    public Jedis getConnection() {
        return getConnection(DEFAULT_REDIS_DB);
    }

    public Jedis getConnection(int db) {
        try {
            Jedis conn = jedisPool.getResource();
            conn.select(db);
            return conn;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    private void close(Jedis jedis) {
        try {
            if (jedis != null) {
                jedis.close();
            }
        } catch (Exception e) {

        }
    }


    public boolean set(String key, String value, int expireSeconds) {
        Jedis jedis = null;
        try {
            jedis = getConnection();
            jedis.set(key, value);
            jedis.expire(key, expireSeconds);
        } catch (Exception e) {
        } finally {
            close(jedis);
        }
        return true;
    }

    public boolean set(String key, String value) {
        Jedis jedis = null;
        boolean flag = true;
        try {
            jedis = getConnection();
            if(null != value){
                jedis.set(key, value);
            }
        } catch (Exception e) {
            flag = false;
        } finally {
            close(jedis);
        }
        return flag;
    }

    public String setLock(String key, int milliseconds) {
        Jedis jedis = null;
        try {
            jedis = getConnection();
            return jedis.set(key, "1", "NX", "PX", milliseconds);
        } catch (Exception e) {
        } finally {
            close(jedis);
        }
        return "";
    }
}
